import {
  LayerConfig,
  LayerType,
  addLayer,
  removeLayer,
  moveLayerBelow,
} from "../layer/layerManage";
import {
  createPopup,
  getPopupById,
  updatePopup,
  updatePopupPositition,
  openPopup,
  closePopup,
} from "@/mapbox/mapbox_core/popup/index.ts";
import { generateLineLayer } from "@/mapbox/mapbox_tool/dataManage/geojson.ts";
import { getLayerManagerState } from "../layer/layerManagerState";
import useInfoDataStore from "@/stores/modules/infoData";

// 类型定义
interface ITrailPoint {
  position: [number, number];
  timestamp: number;
  properties?: Record<string, any>;
}

interface IAircraft {
  id: string;
  points: ITrailPoint[];
  startTime: number;
  endTime: number;
  visible: boolean;
  currentIndex: number;
  lastPosition: [number, number] | null;
  currentBearing: number; // 当前朝向角度(0-360)
  targetBearing: number | null; // 目标朝向角度(移动时)
  bearingTransitionStart: number | null; // 朝向过渡开始时间
  bearingTransitionDuration: number | null; // 朝向过渡持续时间
  animation?: {
    startTime: number;
    duration: number;
    fromPoint: ITrailPoint;
    toPoint: ITrailPoint;
  };
  trailPositions: [number, number][]; // 存储所有航迹点
  passedPoints: ITrailPoint[]; // 已经经过的航迹点
  popup?: any; // 飞机popup
  highlightTrailLayerId?: string; // 高亮航迹图层ID
  highlightSegments?: [number, number][][]; // 存储高亮线段数组
}

// 配置常量
const DEFAULT_CONFIG = {
  animationDuration: 1000, // 标准动画时间1秒
  defaultSpeed: 1, // 默认1倍速
  minSpeed: 0.1,
  maxSpeed: 5,
  cleanupInterval: 1000,
  maxFrameRate: 60,
  trailLength: 100, // 最大航迹点数
  trailColor: "#1841AF", // 航迹线颜色
  highlightTrailColor: "#00FF00", // 高亮航迹线颜色（绿色）
  transparentColor: "rgba(0,0,0,0)", // 透明颜色
  trailWidth: 2, // 航迹线宽度
  highlightTrailWidth: 4, // 高亮航迹线宽度
  trailOpacity: 0.7, // 航迹线透明度
  showFullTrail: true, // 是否显示完整航迹线
};

const defaultPopupContent = `
<div style="background-color: #fff; border-radius: 6px; font-family: Arial, sans-serif; box-shadow: 0 1px 4px rgba(0,0,0,0.2); min-width: 160px; overflow: hidden;">
  <div style="display: flex; justify-content: space-between; align-items: center; padding: 8px 12px; border-bottom: 1px solid #eee;">
    <div style="color: #0064d2; font-size: 14px; font-weight: 600;">20250609_B650N_01</div>
    <div style="color: #999; cursor: pointer;">
      <svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
        <polyline points="9 18 15 12 9 6"></polyline>
      </svg>
    </div>
  </div>
  <div style="padding: 6px 12px;">
    <div style="display: flex; align-items: center;">
      <svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="#999" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="margin-right: 5px;">
        <circle cx="12" cy="12" r="10"></circle>
        <polyline points="12 6 12 12 16 14"></polyline>
      </svg>
      <span style="color: #666; font-size: 12px;">时间未知</span>
    </div>
  </div>
</div>
`;
export class MultiAircraftReplayController {
  // 定义状态
  public state = {
    map: null as any | null,
    aircrafts: new Map<string, IAircraft>(),
    aircraftss: {},
    currentTime: 0,
    isPlaying: false,
    animationFrameId: null as number | null,
    cleanupTimer: null as NodeJS.Timer | null,
    playbackSpeed: DEFAULT_CONFIG.defaultSpeed,
    lastUpdateTime: 0,
    isDragging: false,
  };

  // 定义配置
  private config = { ...DEFAULT_CONFIG };

  // 构造函数，可以传入配置参数
  constructor(options?: Partial<typeof DEFAULT_CONFIG>) {
    this.config = { ...this.config, ...options };
    // 确保初始速度在合理范围内
    this.state.playbackSpeed = Math.max(
      this.config.minSpeed,
      Math.min(this.config.defaultSpeed, this.config.maxSpeed)
    );
  }

  // 初始化地图
  init(map: any) {
    this.state.map = map;
    this.startCleanupTimer();
    return this;
  }

  // 添加飞机
  addAircraft(id: string, points: ITrailPoint[]) {
    if (points.length < 2) throw new Error("每架飞机至少需要2个轨迹点");
    if (this.state.aircrafts.has(id)) {
      console.warn(`飞机 ID "${id}" 已存在`);
      this.removeAircraft(id);
      // return;
    }

    // 确保时间戳有效
    const validPoints = points.map((point) => {
      if (
        !point.timestamp ||
        isNaN(point.timestamp) ||
        !isFinite(point.timestamp)
      ) {
        console.warn(`检测到无效时间戳，飞机ID: ${id}，将使用当前时间替代`);
        return {
          ...point,
          timestamp: Date.now(),
        };
      }
      return point;
    });

    this.state.aircraftss[id] = validPoints;
    // points.sort((a, b) => a.timestamp - b.timestamp);
    const startTime = validPoints[0].timestamp;
    const endTime = validPoints[validPoints.length - 1].timestamp;

    // 创建一个临时的aircraft对象，用于生成初始弹窗内容
    const tempAircraft: IAircraft = {
      id,
      points: validPoints,
      startTime,
      endTime,
      visible: false,
      currentIndex: 0,
      lastPosition: null,
      currentBearing: 0,
      targetBearing: 0,
      bearingTransitionStart: 0,
      bearingTransitionDuration: 0,
      trailPositions: [],
      passedPoints: [],
      highlightSegments: [],
    };

    // 生成初始弹窗内容
    const initialPopupContent = validPoints[0].properties
      ? this.generatePopupContent(tempAircraft)
      : defaultPopupContent;

    // 添加飞机弹窗
    const popup = createPopup(
      this.state.map,
      id + "popup",
      validPoints[0].position,
      initialPopupContent
    );

    // 生成高亮航迹图层ID
    const highlightTrailLayerId = `${id}-highlight-trail`;

    this.state.aircrafts.set(id, {
      ...tempAircraft,
      popup,
      highlightTrailLayerId,
    });

    // 处理预设航线
    const coordinates = validPoints.map((point) => point.position);
    this.generatePredefinedRoutes(id, coordinates);
    // 先添加普通航迹线图层
    this.addTrailLineLayer(id);
    // 添加高亮航迹线图层
    this.addHighlightTrailLayer(highlightTrailLayerId, id);
    // 后添加飞机标记
    this.addAircraftMarker(id, validPoints[0]);

    return this;
  }

  // 添加飞机标记
  private addAircraftMarker(id: string, point: ITrailPoint) {
    const layer: LayerConfig = {
      id: `${id}`,
      type: LayerType.Symbol,
      source: {
        type: "geojson",
        data: {
          type: "FeatureCollection",
          features: [
            {
              type: "Feature",
              geometry: {
                type: "Point",
                coordinates: point.position,
              },
              properties: { id },
            },
          ],
        },
      },
      layout: {
        "icon-image": "airport-15",
        "icon-size": 2,
        "text-field": ["get", "id"],
        "text-font": ["MicrosoftYaHei"],
        "text-size": 16,
        "text-anchor": "top",
        "text-offset": [0, -2.2],
        "text-allow-overlap": true,
      },
      paint: {
        "text-color": "#ffffff",
        "text-halo-color": "#000000",
        "text-halo-width": 2,
        "text-opacity": 0.95,
      },
    };

    addLayer(getLayerManagerState(this.state.map), layer);
  }

  // 添加普通航迹线图层
  private addTrailLineLayer(id: string) {
    const trailLayerId = `${id}-trail`;
    const layer: LayerConfig = {
      id: trailLayerId,
      type: LayerType.Line,
      source: {
        type: "geojson",
        data: {
          type: "FeatureCollection",
          features: [
            {
              type: "Feature",
              geometry: {
                type: "LineString",
                coordinates: [],
              },
              properties: {},
            },
          ],
        },
      },
      paint: {
        "line-color": this.config.trailColor,
        "line-width": this.config.trailWidth,
        "line-opacity": this.config.trailOpacity,
      },
    };

    addLayer(getLayerManagerState(this.state.map), layer);
  }

  // 添加高亮航迹线图层，默认为透明
  private addHighlightTrailLayer(
    highlightTrailLayerId: string,
    aircraftId: string
  ) {
    const { lineLayer } = generateLineLayer(highlightTrailLayerId, [], {
      lineColor: this.config.highlightTrailColor,
      lineWidth: this.config.highlightTrailWidth,
    });

    addLayer(getLayerManagerState(this.state.map), lineLayer);
    // moveLayerBelow(getLayerManagerState(this.state.map), highlightTrailLayerId, aircraftId);
  }

  // 更新航迹线（包括普通和高亮）
  private updateTrailLine(id: string, positions: [number, number][]) {
    const aircraft = this.state.aircrafts.get(id);
    if (!aircraft) return;

    // 更新普通航迹线
    const trailLayerId = `${id}-trail`;
    const trailSource = this.state.map?.getSource(trailLayerId) as any;
    if (trailSource) {
      const features = [
        {
          type: "Feature",
          geometry: {
            type: "LineString",
            coordinates: positions,
          },
          properties: {},
        },
      ];

      trailSource.setData({
        type: "FeatureCollection",
        features: features,
      });
    }
  }

  private trimHighlightTrailBeforeTime(aircraftId: string, time: number) {
    const aircraft = this.state.aircrafts.get(aircraftId);
    if (!aircraft) return;

    // 过滤出指定时间之后的点
    aircraft.passedPoints = aircraft.passedPoints.filter(
      (p) => p.timestamp >= time
    );

    // 同步更新高亮线段
    this.syncHighlightTrailWithTimeline(aircraftId);
  }

  // 更新高亮航迹线 - 智能处理催化剂间断情况
  private updateLiveHighlightTrailLine(
    aircraftId: string,
    currentPosition: [number, number]
  ) {
    const aircraft = this.state.aircrafts.get(aircraftId);
    if (!aircraft || !aircraft.highlightTrailLayerId) return;

    // 只处理当前点是催化剂的情况
    const currentPoint = aircraft.points[aircraft.currentIndex];
    if (currentPoint?.properties?.typesAndDosagesOfCatalysts === "") return;

    // 获取所有已通过的催化剂点
    const catalystPoints = aircraft.passedPoints
      .filter((p) => p.properties?.typesAndDosagesOfCatalysts !== "")
      .map((p) => p.position);

    // 添加当前点（如果是催化剂）
    catalystPoints.push(currentPosition);

    // 更新线段
    const highlightSource = this.state.map?.getSource(
      aircraft.highlightTrailLayerId
    ) as any;
    if (highlightSource) {
      highlightSource.setData({
        type: "FeatureCollection",
        features:
          catalystPoints.length >= 2
            ? [
                {
                  type: "Feature",
                  geometry: {
                    type: "LineString",
                    coordinates: catalystPoints,
                  },
                  properties: {},
                },
              ]
            : [],
      });
    }
  }
  // 计算两点间距离（简化版）
  private calculateDistance(pos1: [number, number], pos2: [number, number]) {
    const dx = pos1[0] - pos2[0];
    const dy = pos1[1] - pos2[1];
    return Math.sqrt(dx * dx + dy * dy);
  }

  // 开始播放
  start() {
    if (!this.state.map || this.state.aircrafts.size === 0) return;

    this.state.isPlaying = true;
    this.state.currentTime = this.getEarliestStartTime();
    this.state.lastUpdateTime = performance.now();

    // 使用requestAnimationFrame进行动画循环
    this.animationLoop();
  }

  // 动画循环
  private animationLoop() {
    if (!this.state.isPlaying || this.state.isDragging) return;

    const now = performance.now();
    const deltaTime = now - this.state.lastUpdateTime;
    this.state.lastUpdateTime = now;

    // 应用播放速度
    const scaledDeltaTime = deltaTime * this.state.playbackSpeed;
    this.state.currentTime += scaledDeltaTime;

    // 检查是否结束
    if (this.state.currentTime >= this.getLatestEndTime()) {
      this.stop();
      return;
    }

    this.updateAllAircraftPositions();
    this.state.animationFrameId = requestAnimationFrame(() =>
      this.animationLoop()
    );
  }

  // 暂停播放
  pause() {
    this.state.isPlaying = false;
    this.cancelAnimation();
  }

  // 停止播放
  stop() {
    this.pause();
    this.state.aircrafts.forEach((aircraft) => {
      this.hideAircraft(aircraft.id);
      // 移除航迹线图层
      const trailLayerId = `${aircraft.id}-trail`;
      removeLayer(getLayerManagerState(this.state.map), trailLayerId);
      // 移除高亮航迹线图层
      this.removeHighlightTrailLayer(aircraft.id);
    });
    this.state.aircrafts.clear();
    this.state.currentTime = 0;
    this.state.playbackSpeed = this.config.defaultSpeed;
  }

  // 更新所有飞机的位置
  private updateAllAircraftPositions() {
    this.state.aircrafts.forEach((aircraft) => {
      // 移除了 !aircraft.visible 的检查，总是更新位置
      // 如果没有进行中的动画，检查是否需要开始新动画
      if (!aircraft.animation) {
        this.checkAndStartNewAnimation(aircraft);
        return;
      }

      // 更新进行中的动画
      this.updateAircraftAnimation(aircraft);
    });
  }

  // 检查并开始新的动画
  private checkAndStartNewAnimation(aircraft: IAircraft) {
    const currentIndex = aircraft.currentIndex;
    const nextIndex = currentIndex + 1;

    if (nextIndex >= aircraft.points.length) {
      this.finalizePosition(aircraft);
      return;
    }

    const currentPoint = aircraft.points[currentIndex];
    const nextPoint = aircraft.points[nextIndex];

    // 检查时间戳有效性
    if (
      !currentPoint.timestamp ||
      !nextPoint.timestamp ||
      isNaN(currentPoint.timestamp) ||
      isNaN(nextPoint.timestamp)
    ) {
      console.warn(`检测到无效时间戳，飞机ID: ${aircraft.id}，跳过此动画`);
      aircraft.currentIndex++;
      this.checkAndStartNewAnimation(aircraft);
      return;
    }

    // 跳过位置相同的点
    if (
      currentPoint.position[0] === nextPoint.position[0] &&
      currentPoint.position[1] === nextPoint.position[1]
    ) {
      aircraft.currentIndex++;
      this.checkAndStartNewAnimation(aircraft);
      return;
    }

    if (this.state.currentTime >= currentPoint.timestamp) {
      const timeDiff = nextPoint.timestamp - currentPoint.timestamp;

      // 确保时间差是有效的正数
      const validTimeDiff = timeDiff > 0 ? timeDiff : 1000; // 默认1秒

      // 考虑播放速度调整动画持续时间
      const scaledDuration =
        (this.config.animationDuration * (validTimeDiff / 1000)) /
        this.state.playbackSpeed;

      aircraft.animation = {
        startTime: performance.now(),
        duration: scaledDuration,
        fromPoint: currentPoint,
        toPoint: nextPoint,
      };

      this.updateAircraftPosition(
        aircraft.id,
        currentPoint.position,
        nextPoint.position,
        0
      );

      // 更新飞机弹窗
      this.updatePopupContent(aircraft.id, "", currentPoint.position);
    }
  }

  // 更新进行中的动画
  private updateAircraftAnimation(aircraft: IAircraft) {
    if (!aircraft.animation) return;

    const now = performance.now();
    const elapsed = now - aircraft.animation.startTime;
    const progress = Math.min(elapsed / aircraft.animation.duration, 1);

    const newPosition = this.lerpPosition(
      aircraft.animation.fromPoint.position,
      aircraft.animation.toPoint.position,
      progress
    );

    this.updateAircraftPosition(
      aircraft.id,
      aircraft.animation.fromPoint.position,
      aircraft.animation.toPoint.position,
      progress
    );

    this.updateAircraftTrail(aircraft, newPosition);
    this.updateAircraftBearing(aircraft, now);
    // 无论当前是否是催化剂点都调用更新
    this.updateLiveHighlightTrailLine(aircraft.id, newPosition);
    if (progress >= 1) {
      // 动画结束时，将当前点添加到已通过点列表
      aircraft.passedPoints.push(aircraft.points[aircraft.currentIndex]);
      aircraft.currentIndex++;
      aircraft.animation = undefined;
      aircraft.currentBearing =
        aircraft.targetBearing || aircraft.currentBearing;
      aircraft.targetBearing = null;
      this.checkAndStartNewAnimation(aircraft);
    }
  }

  // 更新飞机航迹
  private updateAircraftTrail(
    aircraft: IAircraft,
    newPosition: [number, number]
  ) {
    // 如果配置为显示完整航迹线
    if (this.config.showFullTrail) {
      // 添加所有已经经过的点
      aircraft.trailPositions = aircraft.passedPoints.map((p) => p.position);
      // 添加当前位置
      aircraft.trailPositions.push(newPosition);
    } else {
      // 原始逻辑，只保留最近一段
      aircraft.trailPositions.push(newPosition);
      if (aircraft.trailPositions.length > this.config.trailLength) {
        aircraft.trailPositions.shift();
      }
    }

    this.updateTrailLine(aircraft.id, aircraft.trailPositions);
  }

  // 更新飞机的朝向
  private updateAircraftBearing(aircraft: IAircraft, currentTime: number) {
    if (!aircraft.animation) return;

    const fromPos = aircraft.animation.fromPoint.position;
    const toPos = aircraft.animation.toPoint.position;
    const newBearing = this.calculateBearing(fromPos, toPos);

    // 如果朝向需要改变
    if (
      aircraft.targetBearing === null ||
      Math.abs(aircraft.targetBearing - newBearing) > 1
    ) {
      aircraft.targetBearing = newBearing;
      aircraft.bearingTransitionStart = currentTime;
      aircraft.bearingTransitionDuration = 1000; // 1秒内完成转向
    }

    // 计算当前朝向(平滑过渡)
    if (aircraft.bearingTransitionStart && aircraft.bearingTransitionDuration) {
      const bearingProgress = Math.min(
        (currentTime - aircraft.bearingTransitionStart) /
          aircraft.bearingTransitionDuration,
        1
      );

      aircraft.currentBearing = this.lerpAngle(
        aircraft.currentBearing,
        aircraft.targetBearing,
        bearingProgress
      );
    } else {
      aircraft.currentBearing =
        aircraft.targetBearing || aircraft.currentBearing;
    }

    // 应用当前朝向
    this.state.map?.setLayoutProperty(
      aircraft.id,
      "icon-rotate",
      aircraft.currentBearing
    );
  }

  // 平滑过渡角度
  private lerpAngle(start: number, end: number, t: number): number {
    // 处理角度环绕问题
    const shortestAngle = ((((end - start) % 360) + 540) % 360) - 180;
    return start + shortestAngle * t;
  }

  // 更新飞机的位置
  private updateAircraftPosition(
    aircraftId: string,
    fromPosition: [number, number],
    toPosition: [number, number],
    progress: number
  ) {
    const aircraft = this.state.aircrafts.get(aircraftId);
    if (!aircraft) return;

    // 使用插值计算当前位置
    const currentPosition = this.lerpPosition(
      fromPosition,
      toPosition,
      progress
    );

    // 更新地图上的标记位置
    const source = this.state.map?.getSource(aircraftId);
    if (source) {
      source.setData({
        type: "FeatureCollection",
        features: [
          {
            type: "Feature",
            geometry: {
              type: "Point",
              coordinates: currentPosition,
            },
            properties: { id: aircraftId },
          },
        ],
      });
    }

    // 更新弹窗位置和内容
    if (aircraft.popup) {
      this.updatePopupContent(aircraftId, "", currentPosition);
    }

    // 保存当前位置
    aircraft.lastPosition = currentPosition;

    // 更新完飞机位置后，更新高亮航迹线
    if (this.state.isPlaying) {
      this.updateLiveHighlightTrailLine(aircraftId, currentPosition);
    }
  }

  // 计算朝向的函数
  calculateBearing = (
    start: [number, number],
    end: [number, number]
  ): number => {
    const startLng = (start[0] * Math.PI) / 180;
    const startLat = (start[1] * Math.PI) / 180;
    const endLng = (end[0] * Math.PI) / 180;
    const endLat = (end[1] * Math.PI) / 180;

    const y = Math.sin(endLng - startLng) * Math.cos(endLat);
    const x =
      Math.cos(startLat) * Math.sin(endLat) -
      Math.sin(startLat) * Math.cos(endLat) * Math.cos(endLng - startLng);
    const bearing = (Math.atan2(y, x) * 180) / Math.PI;
    return (bearing + 360) % 360;
  };

  // 最终位置
  private finalizePosition(aircraft: IAircraft) {
    const lastPoint = aircraft.points[aircraft.points.length - 1];
    this.updateAircraftPosition(
      aircraft.id,
      lastPoint.position,
      lastPoint.position,
      1
    );
    // 保持最后朝向不变
    this.state.map?.setLayoutProperty(
      aircraft.id,
      "icon-rotate",
      aircraft.currentBearing
    );
    aircraft.currentIndex = aircraft.points.length - 1;
  }

  // 显示飞机 - 只处理显示相关逻辑
  public showAircraft(id: string) {
    const aircraft = this.state.aircrafts.get(id);
    if (!aircraft || aircraft.visible) return;

    // 显示所有相关图层
    this.showRelatedLayers(id);

    aircraft.visible = true;
  }

  // 隐藏飞机 - 只处理隐藏相关逻辑
  public hideAircraft(id: string) {
    const aircraft = this.state.aircrafts.get(id);
    if (!aircraft || !aircraft.visible) return;

    // 隐藏所有相关图层
    this.hideRelatedLayers(id);

    aircraft.visible = false;
  }

  // 显示飞机相关的所有图层
  private showRelatedLayers(id: string) {
    const aircraftLayerId = id;
    const trailLayerId = `${id}-trail`;
    const predefinedRouteLayerId = `${id}-predefined-route`;
    const predefinedRouteTextLayerId = `${id}-predefined-route-text`;
    const highlightTrailLayerId = `${id}-highlight-trail`;

    if (this.state.map) {
      this.state.map.setLayoutProperty(
        aircraftLayerId,
        "visibility",
        "visible"
      );
      this.state.map.setLayoutProperty(trailLayerId, "visibility", "visible");
      this.state.map.setLayoutProperty(
        predefinedRouteLayerId,
        "visibility",
        "visible"
      );
      this.state.map.setLayoutProperty(
        predefinedRouteTextLayerId,
        "visibility",
        "visible"
      );
      this.state.map.setLayoutProperty(
        highlightTrailLayerId,
        "visibility",
        "visible"
      );
    }
  }

  // 隐藏飞机相关的所有图层
  private hideRelatedLayers(id: string) {
    const aircraftLayerId = id;
    const trailLayerId = `${id}-trail`;
    const predefinedRouteLayerId = `${id}-predefined-route`;
    const predefinedRouteTextLayerId = `${id}-predefined-route-text`;
    const highlightTrailLayerId = `${id}-highlight-trail`;

    if (this.state.map) {
      this.state.map.setLayoutProperty(aircraftLayerId, "visibility", "none");
      this.state.map.setLayoutProperty(trailLayerId, "visibility", "none");
      this.state.map.setLayoutProperty(
        predefinedRouteLayerId,
        "visibility",
        "none"
      );
      this.state.map.setLayoutProperty(
        predefinedRouteTextLayerId,
        "visibility",
        "none"
      );
      this.state.map.setLayoutProperty(
        highlightTrailLayerId,
        "visibility",
        "none"
      );
    }
  }

  // 取消动画
  private cancelAnimation() {
    if (this.state.animationFrameId) {
      cancelAnimationFrame(this.state.animationFrameId);
      this.state.animationFrameId = null;
    }
  }

  // 平滑过渡位置
  private lerpPosition(
    from: [number, number],
    to: [number, number],
    t: number
  ): [number, number] {
    return [from[0] + (to[0] - from[0]) * t, from[1] + (to[1] - from[1]) * t];
  }

  // 设置播放速度
  public setSpeed(speed: number) {
    const clampedSpeed = Math.max(
      this.config.minSpeed,
      Math.min(speed, this.config.maxSpeed)
    );
    this.state.playbackSpeed = clampedSpeed;
    this.state.lastUpdateTime = performance.now();

    // 强制重置所有飞机的动画
    this.state.aircrafts.forEach((aircraft) => {
      if (aircraft.animation) {
        aircraft.animation.duration =
          (this.config.animationDuration *
            ((aircraft.animation.toPoint.timestamp -
              aircraft.animation.fromPoint.timestamp) /
              1000)) /
          this.state.playbackSpeed;
      }
    });

    if (this.state.isPlaying) {
      this.cancelAnimation();
      this.animationLoop();
    }
  }

  // 设置当前时间 - 去除自动更新显示隐藏方法
  public setCurrentTime(time: number) {
    this.state.currentTime = Math.max(
      0,
      Math.min(time, this.getLatestEndTime())
    );

    this.state.aircrafts.forEach((aircraft) => {
      this.setAircraftPositionDirectly(aircraft, this.state.currentTime);
      // 新增：同步更新高亮线段
      this.syncHighlightTrailWithTimeline(aircraft.id);
      // 刷新高亮线段
      // this.trimHighlightTrailBeforeTime(aircraft.id, time)
    });
  }

  private syncHighlightTrailWithTimeline(aircraftId: string) {
    const aircraft = this.state.aircrafts.get(aircraftId);
    if (!aircraft || !aircraft.highlightTrailLayerId) return;

    // 获取当前时间之前的所有催化剂点
    const passedCatalystPoints = aircraft.passedPoints
      .filter((p) => p.properties?.typesAndDosagesOfCatalysts !== "")
      .map((p) => p.position);

    // 更新高亮线段数据
    const highlightSource = this.state.map?.getSource(
      aircraft.highlightTrailLayerId
    ) as any;
    if (highlightSource) {
      highlightSource.setData({
        type: "FeatureCollection",
        features:
          passedCatalystPoints.length >= 2
            ? [
                {
                  type: "Feature",
                  geometry: {
                    type: "LineString",
                    coordinates: passedCatalystPoints,
                  },
                  properties: {},
                },
              ]
            : [],
      });

      // 确保线段可见性
      this.state.map?.setPaintProperty(
        aircraft.highlightTrailLayerId,
        "line-opacity",
        passedCatalystPoints.length >= 2 ? 0.9 : 0
      );
    }
  }

  // 更改popup内容，和位置
  public updatePopupContent(
    id: string,
    content: string,
    position: [number, number]
  ) {
    const aircraft = this.state.aircrafts.get(id);
    if (!aircraft || !aircraft.popup) return;

    // 使用自定义内容或者根据aircraft属性生成内容
    let popupContent = content;
    if (!content && aircraft.points[aircraft.currentIndex]?.properties) {
      popupContent = this.generatePopupContent(aircraft);
    }

    aircraft.popup.setHTML(popupContent);
    aircraft.popup.setLngLat(position);
  }

  // 根据飞机属性生成弹窗内容
  private generatePopupContent(aircraft: IAircraft): string {
    const infoData = useInfoDataStore();

    const currentPoint = aircraft.points[aircraft.currentIndex];
    const properties = currentPoint.properties || {};

    // 从属性中获取数据，如果没有则使用默认值
    const flightNo = properties.flightNo || aircraft.id;
    const timestamp = Number(currentPoint.timestamp);
    
    let area = infoData.getDictionaries(flightNo.match(/_(.+?)_/)[1]) || "未知区域";
    // 格式化时间，增加错误处理
    let formattedTime = "时间未知";
    try {
      // 检查时间戳是否有效
      if (timestamp && !isNaN(timestamp)) {
        const date = new Date(timestamp);
        // 检查日期是否有效
        if (!isNaN(date.getTime())) {
          formattedTime = date.toISOString().replace("T", " ").substring(0, 19);
        } else {
          console.warn(`无效的时间戳值: ${timestamp}`);
        }
      }
    } catch (error) {
      console.error(`时间格式化错误:`, error, `时间戳: ${timestamp}`);
    }

    return `
    <div style="background-color: #fff; border-radius: 6px; font-family: Arial, sans-serif; box-shadow: 0 1px 4px rgba(0,0,0,0.2); min-width: 160px; overflow: hidden;">
      <div style="display: flex; justify-content: space-between; align-items: center; padding: 8px 12px; border-bottom: 1px solid #eee;">
        <div style="color: #0064d2; font-size: 14px; font-weight: 600;">${flightNo} / ${area}</div>
      </div>
      <div style="padding: 6px 12px;">
        <div style="display: flex; align-items: center;">
          <svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="#999" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="margin-right: 5px;">
            <circle cx="12" cy="12" r="10"></circle>
            <polyline points="12 6 12 12 16 14"></polyline>
          </svg>
          <span style="color: #666; font-size: 12px;">${formattedTime}</span>
        </div>
      </div>
    </div>
    `;
  }

  // 设置拖拽状态
  public setDraggingState(isDragging: boolean) {
    this.state.isDragging = isDragging;
    if (!isDragging && this.state.isPlaying) {
      // 拖拽结束后恢复播放
      this.start();
    }
  }

  // 直接设置飞机位置（不经过动画）
  private setAircraftPositionDirectly(aircraft: IAircraft, time: number) {
    // 清除任何进行中的动画
    aircraft.animation = undefined;

    // 确保时间在有效范围内
    time = Math.max(aircraft.startTime, Math.min(time, aircraft.endTime));

    // 找到当前时间对应的点
    let currentIndex = 0;
    for (let i = 0; i < aircraft.points.length - 1; i++) {
      // 确保时间戳有效
      if (
        !aircraft.points[i].timestamp ||
        !aircraft.points[i + 1].timestamp ||
        isNaN(aircraft.points[i].timestamp) ||
        isNaN(aircraft.points[i + 1].timestamp)
      ) {
        continue; // 跳过无效时间戳的点
      }

      if (
        time >= aircraft.points[i].timestamp &&
        time < aircraft.points[i + 1].timestamp
      ) {
        currentIndex = i;
        break;
      }
    }

    // 如果时间超过最后一个点，使用最后一个点
    if (time >= aircraft.points[aircraft.points.length - 1].timestamp) {
      currentIndex = aircraft.points.length - 1;
    }

    aircraft.currentIndex = currentIndex;
    aircraft.passedPoints = aircraft.points.slice(0, currentIndex + 1);

    const currentPoint = aircraft.points[currentIndex];

    // 如果是最后一个点
    if (currentIndex === aircraft.points.length - 1) {
      this.updateAircraftPosition(
        aircraft.id,
        currentPoint.position,
        currentPoint.position,
        1
      );
      aircraft.trailPositions = aircraft.passedPoints.map((p) => p.position);
      this.updateTrailLine(aircraft.id, aircraft.trailPositions);
      return;
    }

    // 计算两点之间的进度
    const nextPoint = aircraft.points[currentIndex + 1];

    // 检查时间戳有效性
    if (
      !currentPoint.timestamp ||
      !nextPoint.timestamp ||
      isNaN(currentPoint.timestamp) ||
      isNaN(nextPoint.timestamp)
    ) {
      // 如果时间戳无效，直接使用当前点位置
      this.updateAircraftPosition(
        aircraft.id,
        currentPoint.position,
        currentPoint.position,
        1
      );
      aircraft.trailPositions = aircraft.passedPoints.map((p) => p.position);
      this.updateTrailLine(aircraft.id, aircraft.trailPositions);
      return;
    }

    const segmentDuration = nextPoint.timestamp - currentPoint.timestamp;
    // 确保段持续时间是正数
    const validSegmentDuration = segmentDuration > 0 ? segmentDuration : 1;
    const elapsed = time - currentPoint.timestamp;
    const progress = Math.min(1, Math.max(0, elapsed / validSegmentDuration));

    // 更新位置
    const newPosition = this.lerpPosition(
      currentPoint.position,
      nextPoint.position,
      progress
    );

    this.updateAircraftPosition(
      aircraft.id,
      currentPoint.position,
      nextPoint.position,
      progress
    );

    // 更新航迹
    aircraft.trailPositions = [
      ...aircraft.passedPoints.map((p) => p.position),
      newPosition,
    ];

    this.updateTrailLine(aircraft.id, aircraft.trailPositions);

    // 更新朝向
    const bearing = this.calculateBearing(
      currentPoint.position,
      nextPoint.position
    );
    aircraft.currentBearing = bearing;
    this.state.map?.setLayoutProperty(aircraft.id, "icon-rotate", bearing);
  }

  // 获取最早开始时间
  private getEarliestStartTime() {
    return this.state.aircrafts.size === 0
      ? 0
      : Math.min(
          ...Array.from(this.state.aircrafts.values()).map((a) => a.startTime)
        );
  }

  // 获取最晚结束时间
  private getLatestEndTime() {
    return this.state.aircrafts.size === 0
      ? 0
      : Math.max(
          ...Array.from(this.state.aircrafts.values()).map((a) => a.endTime)
        );
  }

  private startCleanupTimer() {
    if (this.state.cleanupTimer) return;
    this.state.cleanupTimer = setInterval(() => {
      // 清理逻辑可以在这里添加
    }, this.config.cleanupInterval);
  }

  // 移除高亮航迹线图层
  private removeHighlightTrailLayer(id: string) {
    const aircraft = this.state.aircrafts.get(id);
    if (!aircraft) return;

    const highlightTrailLayerId = aircraft.highlightTrailLayerId;
    if (!highlightTrailLayerId) return;

    removeLayer(getLayerManagerState(this.state.map), highlightTrailLayerId);
  }

  // 删除指定ID的飞机及其航迹线
  public removeAircraft(id: string) {
    const aircraft = this.state.aircrafts.get(id);
    if (!aircraft) {
      console.warn(`飞机 ID "${id}" 不存在`);
      return;
    }

    // 隐藏飞机
    this.hideAircraft(id);

    // 移除飞机标记图层
    if (this.state.map) {
      removeLayer(getLayerManagerState(this.state.map), id);
    }

    // 移除航迹线图层
    const trailLayerId = `${id}-trail`;
    if (this.state.map) {
      removeLayer(getLayerManagerState(this.state.map), trailLayerId);
    }

    // 移除高亮航迹线图层
    this.removeHighlightTrailLayer(id);

    // 移除预设航线图层
    const predefinedRouteLayerId = `${id}-predefined-route`;
    if (this.state.map) {
      removeLayer(getLayerManagerState(this.state.map), predefinedRouteLayerId);
      removeLayer(
        getLayerManagerState(this.state.map),
        `${id}-predefined-route-text`
      );
    }

    // 移除popup
    closePopup(id + "popup");

    // 从飞机集合中删除
    this.state.aircrafts.delete(id);
  }

  // 删除所有飞机及其航迹线
  public removeAllAircraft() {
    // 暂停播放
    this.pause();

    // 遍历并删除所有飞机
    this.state.aircrafts.forEach((aircraft) => {
      this.removeAircraft(aircraft.id);
    });

    // 清空飞机集合
    this.state.aircrafts.clear();
    this.state.currentTime = 0;
  }

  // 生成预设航线
  private generatePredefinedRoutes(id: string, coordinates: any) {
    // 生成图层配置
    const { source, lineLayer, textLayer } = generateLineLayer(
      `${id}-predefined-route`,
      coordinates,
      {
        lineColor: "#696969",
        lineWidth: 4,
        withText: true,
        textField: id + "(预设航线)",
        textColor: "#ffffff",
        textSize: 16,
      }
    );
    // console.log(source, lineLayer, textLayer);

    addLayer(getLayerManagerState(this.state.map), lineLayer);
    addLayer(getLayerManagerState(this.state.map), textLayer);
    // console.log("生成预设航迹线");
  }
}
